const express = require('express')
const goodsRouter = express.Router()

//菜品列表
const goodsList = [
	{ id: 1, name: '回锅肉', price: 18.88, num: 10 },
	{ id: 2, name: '鱼香肉丝', price: 28.75, num: 5 },
]

/**
 * 菜品列表
 */
goodsRouter.get('/goods', (req, res) => {
	res.send({
		code: 1,
		list: goodsList,
	})
})

/**
 * 查询商品
 *  method: get 
 *  url:    /goods/1
 */
goodsRouter.get('/goods/:id',(req,res)=>{
	const id = req.params.id

	const good =  goodsList.find(item=>item.id == id)

	res.send({
		code:1,
		good:good
	})
})

/**
 * 添加商品
 *  get请求参数 query
 *  http://ip:port/goods/add?name=''
 * 
 *   post请求的参数存储在请求体中 body中
 */
goodsRouter.post('/goods', (req, res) => {
	//接收参数
	const id = req.body.id
	const name = req.body.name
	const price = req.body.price
	const num = req.body.num
	//添加到数组
	goodsList.push({
		id,
		name,
		price,
		num,
	})
	//响应
	res.send({
		code: 1,
		message: '添加商品成功!',
	})
})

/**
 * 删除商品
 * 根据商品ID删除商品
 *  delete /goods/1
 *  delete /goods/2
 */
goodsRouter.delete('/goods/:id', (req, res) => {
	//接收参数
	const id = req.params.id
	//删除数组元素
	const index = goodsList.findIndex(item => item.id == id)
	goodsList.splice(index, 1)
	//响应
	res.send({
		code: 1,
		message: '删除商品成功!',
	})
})

/**
 * 修改商品价格
 * 根据商品id
 *   method: put
 *   url: /goods/1
 *   参数: price:number
 *   响应： 
 */
goodsRouter.put('/goods/:id',(req,res)=>{
	const id = req.params.id
	const price = req.body.price
	//修改商品
	goodsList.forEach(item=>{
		if(item.id == id){
			item.price = price
		}
	})
	res.send({
		code:1,
		message:'修改商品成功!'
	})
})


module.exports = { goodsRouter }
